﻿// 项目：	Guan.CMS.Web - Guan.CMS
// 文件名：	Bootstrapper.cs
// 
// 修改时间：2013-03-06 19:53
// 修改人：	Cooclsee

using System.Reflection;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Guan.CMS.CommandProcessor.Command;
using Guan.CMS.CommandProcessor.Dispatcher;
using Guan.CMS.Data.Infrastructure;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Services;
using Guan.CMS.Web.Core.Authentication;
using Guan.CMS.Web.Mappers;

namespace Guan.CMS.Web
{
    public class Bootstrapper
    {
        public static void Run()
        {
            SetAutofacContainer();
            AutoMapperConfiguration.Configure();
        }

        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<DefaultCommandBus>().As<ICommandBus>().InstancePerHttpRequest();
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerHttpRequest();
            builder.RegisterAssemblyTypes(typeof(SiteConfigRepository).Assembly)
                   .Where(t => t.Name.EndsWith("Repository"))
                   .AsImplementedInterfaces()
                   .InstancePerHttpRequest();
            builder.RegisterAssemblyTypes(typeof(ProductCategoryService).Assembly)
                   .Where(t => t.Name.EndsWith("Service"))
                   .AsImplementedInterfaces()
                   .InstancePerHttpRequest();
            var services = Assembly.Load("Guan.CMS.Domain");
            builder.RegisterAssemblyTypes(services).AsClosedTypesOf(typeof (ICommandHandler<>)).InstancePerHttpRequest();
            builder.RegisterAssemblyTypes(services)
                   .AsClosedTypesOf(typeof (IValidationHandler<>))
                   .InstancePerHttpRequest();
            builder.RegisterType<DefaultFormsAuthentication>().As<IFormsAuthentication>().InstancePerHttpRequest();
            builder.RegisterFilterProvider();
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}